import { Component, OnInit, Host } from "@angular/core";
import { InsightsService } from "../insights.service";
import { AppComponent } from "../../../../app.component";
import { ActivatedRoute, Router } from "@angular/router";
import { ToasterService } from "angular2-toaster";
import { EventStatus, EventModel } from "../../events/models/events.model";
import { InsightsModel, InsightStatus } from "../model/insights.model";
import { NameModel } from "../model/insightsNames.model";
import { FileUploader, FileUploaderOptions } from "ng2-file-upload";
import { StorageService } from "../../../../shared/services/storage.service";

@Component({
    templateUrl: 'insight.component.html'
})
export class InsightComponent implements OnInit {
    public insight: InsightsModel;
    public edit: string = 'false';
    public canEdit: boolean = false;
    public topics: NameModel[];
    public sectors: NameModel[];
    public quillOptions: any = {
        toolbar: [
            ['bold', 'italic', 'underline', 'strike'],        // toggled buttons            
            [{ 'size': ['small', false, 'large', 'huge'] }],  // custom dropdown
            [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
            ['link']                         // link and image, video
        ]
    }
    public imageUploader: FileUploader;
    public fileUploader: FileUploader;
    public fileSuccess: boolean;

    constructor(@Host() private rootComponent: AppComponent,
        private insightsService: InsightsService,
        private route: ActivatedRoute,
        private router: Router,
        private toasterService: ToasterService) { }

    ngOnInit(): void {        
        this.imageUploader = new FileUploader({});
        this.fileUploader = new FileUploader({});
        
        this.insightsService.getInsightsNames().subscribe(data => {
            this.topics = data.topicNames;
            this.sectors = data.sectorNames;
        });

        this.route.params.subscribe(param => {
            this.edit = param['edit'];
            if (this.edit == 'true') {
                this.insightsService.getInsight(param['id']).subscribe(data => {
                    this.insight = this.loadData(data);
                    this.canEdit = this.insight.state == InsightStatus.Draft;
                });
            }
            else {
                this.insight = new InsightsModel();
                this.insight.insightSectorId = null;
                this.insight.insightTopicId = null;
                this.canEdit = true;
            }
            this.rootComponent.finishLoading();
        });

        this.imageUploader.onAfterAddingFile = (data: any) => {
            let auth = StorageService.get().authData;
            this.imageUploader.authToken = `Bearer ${auth.access_token}`;
            data.withCredentials = false;            
            this.imageUploader.setOptions(
                {
                    url: this.insightsService.getUploadUrl() + this.insight.imageId,
                    method: this.edit == 'true' ? 'PUT' : 'POST',
                    headers: [
                        { name: 'Content-Disposition', value: 'attachment; filename="' + data.file.name + '"' }, 
                        { name: 'Content-Type', value: data.file.type }
                    ]
                }
            );
            this.imageUploader.uploadAll();
        }

        this.imageUploader.onSuccessItem = (item: any, response: any, status: any, headers: any) => {
            this.toasterService.pop('success', 'Success', 'Image uploaded successfully');
            let data = JSON.parse(response);
            this.insight.imageId = data.id;
            this.insight.imageUrl = data.fileUrl + "_" + item.file.name;
            this.insight.imageS3Name = data.id + "_" + item.file.name;
        };

        this.fileUploader.onAfterAddingFile = (data: any) => {
            let auth = StorageService.get().authData;
            this.fileUploader.authToken = `Bearer ${auth.access_token}`;
            data.withCredentials = false;            
            this.fileUploader.options.url = this.insightsService.getUploadUrl() + this.insight.fileId;       
            this.fileUploader.options.method = this.edit == 'true' ? 'PUT' : 'POST';
            this.fileUploader.options.headers = [
                { name: 'Content-Disposition', value: 'attachment; filename="' + data.file.name + '"' }, 
                { name: 'Content-Type', value: data.file.type }
            ];
            this.fileUploader.uploadAll();
        }

        this.fileUploader.onSuccessItem = (item: any, response: any, status: any, headers: any) => {
            this.toasterService.pop('success', 'Success', 'File uploaded successfully');
            let data = JSON.parse(response);
            this.insight.fileId = data.id;
            this.insight.fileUrl = data.fileUrl + "_" + item.file.name;
            this.insight.fileName = item.file.name;
            this.insight.fileS3Name = data.id + "_" + item.file.name;
            this.fileSuccess = item.isSuccess;
        };
    }

    private loadData(insight: InsightsModel): InsightsModel {
        if (insight.datePublished)
            insight.datePublished = new Date(insight.datePublished);
        if (insight.dateUnPublished)
            insight.dateUnPublished = new Date(insight.dateUnPublished);
        return insight;
    }

    public publishInsight() {
        if (this.validInsight()) {
            this.saveData(InsightStatus.Published);
        }
    }

    public saveInsight() {
        if (this.validInsight()) {
            this.saveData(InsightStatus.Draft);
        }
    }

    private validInsight(): boolean {
        let ret: boolean = true;
        /*  if (!this.event.name) {
             this.toasterService.pop('warning', 'Warning', 'Event name required.');
             ret = false;
         }
 
         if (this.event.startDate && this.event.endDate) {
             if (moment(this.event.startDate) > moment(this.event.endDate)) {
                 this.toasterService.pop('warning', 'Warning', 'End date must be after start date.');
                 ret = false;
             }
         }
         else {
             if (!this.event.startDate) {
                 this.toasterService.pop('warning', 'Warning', 'Start date required');
                 ret = false;
             }
             if (!this.event.endDate) {
                 this.toasterService.pop('warning', 'Warning', 'End date required');
                 ret = false;
             }
         }
 
         if (!this.event.body) {
             this.toasterService.pop('warning', 'Warning', 'Event content required');
             ret = false;
         } */

        return ret;
    }

    private saveData(status: InsightStatus) {
        this.insight.state = status;
        if (this.canEdit && this.edit == 'true')
            this.insightsService.saveInsight(this.insight).subscribe(_ => this.goBack());
        else
            this.insightsService.publishInsight(this.insight).subscribe(_ => this.goBack());
    }

    private goBack() {
        this.router.navigate(['../../'], { relativeTo: this.route });
    }
}